package com.papers.juan.controller;

import java.util.*;
import java.util.concurrent.TimeUnit;

import com.alibaba.excel.util.StringUtils;
import com.papers.common.helper.LoginHelper;
import com.papers.juan.domain.SysFile;
import com.papers.juan.utils.FileType;
import com.papers.juan.utils.FileUtil;
import com.papers.juan.utils.LocalUploadProperties;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.papers.common.annotation.RepeatSubmit;
import com.papers.common.annotation.Log;
import com.papers.common.core.controller.BaseController;
import com.papers.common.core.domain.PageQuery;
import com.papers.common.core.domain.R;
import com.papers.common.core.validate.AddGroup;
import com.papers.common.core.validate.EditGroup;
import com.papers.common.core.validate.QueryGroup;
import com.papers.common.enums.BusinessType;
import com.papers.common.utils.poi.ExcelUtil;
import com.papers.juan.domain.vo.SysFileVo;
import com.papers.juan.domain.bo.SysFileBo;
import com.papers.juan.service.ISysFileService;
import com.papers.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件
 *
 * @author papers
 * @date 2022-11-08
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/juan/file")
public class SysFileController extends BaseController {

    private final ISysFileService iSysFileService;

    private final LocalUploadProperties localUploadProperties;

    /**
     * 查询文件列表
     */
    @SaCheckPermission("juan:file:list")
    @GetMapping("/list")
    public TableDataInfo<SysFileVo> list(SysFileBo bo, PageQuery pageQuery) {
        return iSysFileService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出文件列表
     */
    @SaCheckPermission("juan:file:export")
    @Log(title = "文件", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(SysFileBo bo, HttpServletResponse response) {
        List<SysFileVo> list = iSysFileService.queryList(bo);
        ExcelUtil.exportExcel(list, "文件", SysFileVo.class, response);
    }

    /**
     * 获取文件详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("juan:file:query")
    @GetMapping("/{id}")
    public R<SysFileVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iSysFileService.queryById(id));
    }

    /**
     * 新增文件
     */
    @SaCheckPermission("juan:file:add")
    @Log(title = "文件", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody SysFileBo bo) {
        return toAjax(iSysFileService.insertByBo(bo) ? 1 : 0);
    }

    /**
     * 修改文件
     */
    @SaCheckPermission("juan:file:edit")
    @Log(title = "文件", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody SysFileBo bo) {
        return toAjax(iSysFileService.updateByBo(bo) ? 1 : 0);
    }

    /**
     * 删除文件
     *
     * @param ids 主键串
     */
    @SaCheckPermission("juan:file:remove")
    @Log(title = "文件", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iSysFileService.deleteWithValidByIds(Arrays.asList(ids), true) ? 1 : 0);
    }

    @PostMapping("/upload")
    public Object privatUpload(@RequestParam("file") MultipartFile file, @RequestParam Map<String, Object> params) throws Exception {
        String classify = (String) params.get("classify");// 获取文件业务分类
        String isPublic = (String) params.get("isPublic");// 是否公开
        String dataId = (String) params.get("dataId");// 业务数据id
        String dir = (String) params.get("dir");// 业务数据id
        if (classify == null) {
            return R.fail("获取文件业务类型失败！");
        }
        String fileName = file.getOriginalFilename();// 获取文件名
        fileName = FileUtil.renameToUUID(fileName);// 避免文件名重复覆盖，重命名文件
        SysFile sysFile = new SysFile();
        sysFile.setFileName(file.getOriginalFilename());// 获取原始文件名
        sysFile.setType(FileType.fileType(fileName) + "");// 文件类型 0 图片 1 文档 2视频 3 音频
        Long userId = 1L;
//        Long userId = LoginHelper.getUserId();// 获取上传人id
//        if (userId == null) {
//            throw new RuntimeException("用户未登陆");
//        }
        String url = "/" + classify + "/" + userId + "/";// 拼接文件相对路径
        sysFile.setUrl(url + fileName);// 设置文件相对路径
        sysFile.setCreateTime(new Date());
        sysFile.setClassify(classify);// 业务分类
        sysFile.setCreateUser(userId);// 创建人
        sysFile.setIsDel("0");
//        sysFile.setDownloadNum(0L);
//        sysFile.setIsLibrary(Func.toInt(params.get("isLibrary"), 0));
//        sysFile.setDir(dir);
        if (!StringUtils.isEmpty(dataId)) {
            sysFile.setDataId(Long.valueOf(dataId));
        }
        try {
            FileUtil.uploadFile(file.getBytes(), localUploadProperties.getPublicFilePath() + "/" + url, fileName);
//            sysFile.setFileSize(Func.toStr(file.getBytes().length));// 设置文件大小
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("");
        }

//		sysFile.setUrl(localUploadProperties.getPublicFileMappingDomain() + sysFile.getUrl());
//        if (sysFile.getIsLibrary() == 1) {
//            sysFile.setDirId(0L);
//        }
        SysFileBo sysFileBo = new SysFileBo();
        BeanUtils.copyProperties(sysFile, sysFileBo);
        if (iSysFileService.insertByBo(sysFileBo)) {
            Map<String, Object> ret = new HashMap<String, Object>();
            sysFileBo.setUrl(localUploadProperties.getPublicFileMappingDomain() + sysFileBo.getUrl());
            ret.put("file", sysFileBo);
            return R.ok(ret);
        }
        return R.fail("系统异常，请联系管理员");
    }
}
